package com.ruoyi.project.applet.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.applet.domain.Vip;
import com.ruoyi.project.applet.mapper.VipMapper;
import com.ruoyi.project.applet.service.IVipService;
import com.ruoyi.project.system.domain.SysUserWx;
import com.ruoyi.project.system.mapper.SysUserWxMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;


@Service
public class VipServiceImpl implements IVipService
{
    private Logger logger = LoggerFactory.getLogger("VipServiceImpl");
    @Autowired
    private VipMapper vipMapper;

    @Autowired
    private SysUserWxMapper sysUserWxMapper;
    /**
     * 查询vip充值
     * 
     * @param id vip充值ID
     * @return vip充值
     */
    @Override
    public Vip selectVipById(int id)
    {
        return vipMapper.selectVipById(id);
    }

    /**
     * 查询vip充值列表
     * 
     * @param vip vip充值
     * @return vip充值
     */
    @Override
    public List<Vip> selectVipList(Vip vip)
    {
        return vipMapper.selectVipList(vip);
    }

    /**
     * 新增vip充值
     * 
     * @param vip vip充值
     * @return 结果
     */
    @Override
    public int insertVip(Vip vip)
    {
        Vip vip1 = new Vip();
        vip1.setName(vip.getName());
        List<Vip> vips = vipMapper.selectVipList(vip1);
        Assert.isTrue(vips.size()==0,"会员名称已存在");
        vip.setCreateTime(DateUtils.getNowDate());
        logger.info("会员:{},新增成功",vip.getName());
        return vipMapper.insertVip(vip);
    }

    /**
     * 修改vip充值
     * 
     * @param vip vip充值
     * @return 结果
     */
    @Override
    public int updateVip(Vip vip)
    {
        Vip vip1 = new Vip();
        vip.setUpdateTime(DateUtils.getNowDate());
        logger.info("用户:"+vip.getUpdateBy() + "修改会员"+vip.getName());
        return vipMapper.updateVip(vip);
    }

    /**
     * 批量删除vip充值
     * 
     * @param ids 需要删除的vip充值ID
     * @return 结果
     */
    @Override
    public int deleteVipByIds(Long[] ids)
    {
        return vipMapper.deleteVipByIds(ids);
    }

    /**
     * 删除vip充值信息
     * 
     * @param id vip充值ID
     * @return 结果
     */
    @Override
    public int deleteVipById(Long id)
    {
        return vipMapper.deleteVipById(id);
    }


    //10分钟触发一次
    @Scheduled(cron = "0 1/10 * * * *")
    public void updateVip() {
        List<SysUserWx> vipList = sysUserWxMapper.getVipList();
        Date nowDate = DateUtils.getNowDate();
        for (SysUserWx vip : vipList) {
            if (vip.getExpirationTime().before(nowDate)){
                sysUserWxMapper.updateVip(vip.getUserId());
                logger.info("会员:{},到期了",vip.getUserId());
            }
        }
    }
}
